const Core = require("../../../utils/core.js");
const Pay_wx = require("../../../utils/pay_wx.js");
const BehaviorAll = require("../../../behaviors/behavior_all.js");
const ServiceOrder = require("../../../service/service_order.js");
const ServicePay = require("../../../service/service_pay.js");
const ServiceUser = require("../../../service/service_user.js");
const ServiceTicket = require("../../../service/service_ticket.js");

module.exports = {
  /**
   * behaviors
   */
  behaviors: [BehaviorAll],
  /**
   * 页面的初始数据
   */
  data: {
    /**
     * 订单数据格式
        {
          id: 1,
          name: "法国进口红酒拉斐天使庄园干红葡萄酒红酒整箱礼盒装750ml*6",
          price: 100,
          imgUrl:''
        }
     */
    order: null,
    /**
     * 支付方式：
     *  微信支付 == 1
     *  线下支付 == 2
     */
    payWay: 1,
    /**
     * 用户全部积分
     */
    score: 0,
    currentScore: 0,
    maxScore: 0,
    payPrice: 0, // 支付价格
    /**
     * 电子券
     */
    ticket: null,
    tickets: [],
    showTicketsFlag: false
  },
  /**
   * 监听器
   */
  observers: {
    'order': function (order) {
      const _this = this;
      const ticket = _this.data.ticket;
      const ticketPrice = ticket ? ticket.price : 0;
      const payPrice = order.totalPrice - _this.data.currentScore - ticketPrice;
      _this.setData({ payPrice })
    },
    'ticket': function (ticket) {
      const _this = this;
      const ticketPrice = ticket ? ticket.price : 0;
      const payPrice = _this.data.order.totalPrice - _this.data.currentScore - ticketPrice;
      _this.setData({ payPrice })
    },
    'currentScore': function (currentScore) {
      const _this = this;
      const ticket = _this.data.ticket;
      const ticketPrice = ticket ? ticket.price : 0;
      const payPrice = _this.data.order.totalPrice - currentScore - ticketPrice;
      _this.setData({ payPrice })
    }
  },
  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      const _this = this;
      const orderId = options.orderId;
      // 加载订单数据
      ServiceOrder.findById(orderId, function (orderData) {
        // 获取积分
        ServiceUser.getScore(function (scoreData) {
          const score = scoreData.score;
          // 电子券
          if (orderData.type !== 'Pack') {
            ServiceTicket.findExpiry(function (ticketData) {
              // @TODO 待处理 ticketData 为空的情况
              const ticketPrice = ticketData ? ticketData.price : 0;
              let maxScore = orderData.totalPrice - ticketPrice;
              maxScore = maxScore > score ? score : maxScore;
              _this.setData({
                order: orderData,
                score: score,
                maxScore: maxScore,
                currentScore: maxScore,
                ticket: ticketData
              })
            });
          }else{
            let maxScore = orderData.totalPrice;
            maxScore = maxScore > score ? score : maxScore;
            _this.setData({
              order: orderData,
              score: score,
              maxScore: maxScore,
              currentScore: maxScore
            })
          }
        });
        // 电子券列表
        if (orderData.type !== 'Pack') {
          ServiceTicket.usePage(0, function (data) {
            _this.setData({
              tickets: data.records
            })
          });
        }
      })
    },

    /**
     * 切换支付
     */
    onPayWayChange: function (e) {
      const _this = this;
      _this.setData({
        payWay: e.detail.value
      });
    },

    /**
     * 设置积分
     */
    onScoreChange: function (e) {
      const _this = this;
      const value = e.detail.value;
      //设置
      if (!value.endWith('.') || value.endWith('..')) {
        // 验证
        let socre = parseFloat(value);
        if (isNaN(socre)) {
          socre = 0;
        }
        if (socre < 0) {
          socre = 0;
        }
        if (socre > _this.data.maxScore) {
          wx.showToast({
            title: '不能超出账户余额' + _this.data.maxScore,
            icon: 'none'
          })
          _this.setData({ currentScore: _this.data.maxScore });
          return;
        }

        _this.setData({
          currentScore: socre
        });
      }
    },

    /**
     * 支付
     */
    onPay: function (e) {
      const _this = this;
      const orderId = _this.data.order.id;
      const currentScore = _this.data.currentScore;
      const ticket = _this.data.ticket;
      const ticketId = ticket ? ticket.id : null;
      //
      const payWay = Number(_this.data.payWay);
      if (payWay === 1 || _this.data.payPrice === 0) {
        _this._payWithWx(orderId, ticketId, currentScore);
      } else if (payWay === 2){
        _this._payWithCard(orderId, ticketId, currentScore);
      } else {
        wx.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
      }
    },

    /**
     * 微信支付
     */
    _payWithWx: function (orderId, ticketId, currentScore) {
      // 发起预支付请求
      ServicePay.preparePay(orderId, ticketId, currentScore, function (data, res) {
        if (data === 'Finish') {
          wx.navigateTo({ url: '../../../model_user/pages/order/order?state=3' })
          return;
        }
        Pay_wx.wxRequestPayment(
          data,
          function (res) {
            wx.navigateTo({ url: '../../../model_user/pages/order/order?state=3' })
          }
        );
      })
    },

    /**
     * 线下支付
     */
    _payWithCard: function (orderId, ticketId, currentScore) {
      const _this = this;
      const totalPrice = _this.data.order.totalPrice;
      const ticket = _this.data.ticket;
      const ticketPrice = ticket ? ticket.price : 0;
      //
      // if (currentScore < totalPrice - ticketPrice) {
      //   wx.navigateTo({
      //     url: '../orderUnlinePay/orderUnlinePay?score=' + currentScore + '&orderId=' + orderId + '&ticketPrice=' + ticketPrice + '&ticketId=' + ticketId
      //   })
      // } else {
        ServicePay.payUnderLine(
          orderId,
          ticketId,
          currentScore,
          function () {
            wx.navigateTo({ url: '../../../model_user/pages/order/order?state=2' })
          }
        );
      // }
    },

    /**
     * onShowTickets
     */
    onShowTickets: function (e) {
      const _this = this;
      _this.setData({
        showTicketsFlag: true
      });
    },
    /**
     * onHideTickets
     */
    onHideTickets: function (e) {
      const _this = this;
      _this.setData({
        showTicketsFlag: false
      });
    },

    /**
     * onSelectTicket
     */
    onSelectTicket: function (e) {
      const _this = this;
      const ticket = e.currentTarget.dataset.item;
      // 处理最大积分
      const score = _this.data.score;
      let maxScore = _this.data.order.totalPrice - ticket.price;
      maxScore = maxScore > score ? score : maxScore;
      //
      _this.setData({
        showTicketsFlag: false,
        ticket: ticket,
        currentScore: maxScore,
        maxScore: maxScore
      });
    }
  }

}